using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinLOAtest.Data;
using WinLOAtest.Models;

namespace WinLOAtest.Forms
{
    public partial class FeatureConfigForm : Form
    {
        private List<FeatureConfig> features;

        public FeatureConfigForm()
        {
            InitializeComponent();
            LoadData();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                features = DatabaseHelper.GetAllFeatureConfigs();
                RefreshFeatureList();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新功能列表
        /// </summary>
        private void RefreshFeatureList()
        {
            dataGridViewFeatures.Rows.Clear();
            foreach (var feature in features.OrderBy(f => f.SortOrder))
            {
                dataGridViewFeatures.Rows.Add(
                    feature.FeatureId,
                    feature.FeatureName,
                    feature.Description,
                    feature.IsEnabled ? "启用" : "禁用",
                    feature.SortOrder
                );
            }
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasChanges = false;
                foreach (DataGridViewRow row in dataGridViewFeatures.Rows)
                {
                    if (row.IsNewRow) continue;

                    int featureId = Convert.ToInt32(row.Cells[0].Value);
                    string featureName = row.Cells[1].Value?.ToString() ?? "";
                    string description = row.Cells[2].Value?.ToString() ?? "";
                    bool isEnabled = row.Cells[3].Value?.ToString() == "启用";
                    int sortOrder = Convert.ToInt32(row.Cells[4].Value);

                    var feature = features.FirstOrDefault(f => f.FeatureId == featureId);
                    if (feature != null)
                    {
                        // 检查是否有变化
                        if (feature.FeatureName != featureName ||
                            feature.Description != description ||
                            feature.IsEnabled != isEnabled ||
                            feature.SortOrder != sortOrder)
                        {
                            feature.FeatureName = featureName;
                            feature.Description = description;
                            feature.IsEnabled = isEnabled;
                            feature.SortOrder = sortOrder;

                            bool success = DatabaseHelper.UpdateFeatureConfig(feature);
                            if (success)
                            {
                                hasChanges = true;
                            }
                            else
                            {
                                MessageBox.Show($"更新功能 {featureId} 失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                    }
                }

                if (hasChanges)
                {
                    MessageBox.Show("功能配置保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadData();
                }
                else
                {
                    MessageBox.Show("没有检测到任何变化。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        private void buttonReset_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要重置所有功能配置为默认值吗？", "确认重置", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    // 重置为默认配置
                    for (int i = 1; i <= 20; i++)
                    {
                        var feature = features.FirstOrDefault(f => f.FeatureId == i);
                        if (feature != null)
                        {
                            feature.FeatureName = $"功能{i}";
                            feature.Description = $"按钮{i}是否可用";
                            feature.IsEnabled = true;
                            feature.SortOrder = i;

                            DatabaseHelper.UpdateFeatureConfig(feature);
                        }
                    }

                    MessageBox.Show("功能配置重置成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadData();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"重置失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 数据网格视图单元格值改变事件
        /// </summary>
        private void dataGridViewFeatures_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                // 标记行已修改
                dataGridViewFeatures.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightYellow;
            }
        }

        /// <summary>
        /// 数据网格视图单元格开始编辑事件
        /// </summary>
        private void dataGridViewFeatures_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            // 功能ID列不允许编辑
            if (e.ColumnIndex == 0)
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 数据网格视图单元格格式化事件
        /// </summary>
        private void dataGridViewFeatures_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                // 根据启用状态设置行颜色
                if (e.ColumnIndex == 3) // 状态列
                {
                    string status = e.Value?.ToString();
                    if (status == "启用")
                    {
                        e.CellStyle.ForeColor = Color.Green;
                    }
                    else if (status == "禁用")
                    {
                        e.CellStyle.ForeColor = Color.Red;
                    }
                }
            }
        }

        /// <summary>
        /// 数据网格视图单元格验证事件
        /// </summary>
        private void dataGridViewFeatures_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                // 验证功能名称不能为空
                if (e.ColumnIndex == 1) // 功能名称列
                {
                    if (string.IsNullOrWhiteSpace(e.FormattedValue?.ToString()))
                    {
                        e.Cancel = true;
                        MessageBox.Show("功能名称不能为空！", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                // 验证排序顺序必须是数字
                if (e.ColumnIndex == 4) // 排序顺序列
                {
                    if (!int.TryParse(e.FormattedValue?.ToString(), out int sortOrder) || sortOrder < 1)
                    {
                        e.Cancel = true;
                        MessageBox.Show("排序顺序必须是大于0的整数！", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
    }
}
